package com.llmcu.source.javase.thread.producerandconsumer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Basket {
    List<Mantou> content = new ArrayList<>();

    // 最大容量
    final int MAX_SIZE = 10;

    // 生产一个馒头
    public synchronized void push(Mantou m) throws InterruptedException {
        while(content.size()>=MAX_SIZE){
            System.out.println(Thread.currentThread().getId()+"准备执行push中的wait()");
            wait();
            System.out.println(Thread.currentThread().getId()+"完成执行push中的wait()");
        }
        content.add(m);
        System.out.println(Thread.currentThread().getId()+"生产者生产了一个馒头："+this);
        System.out.println(Thread.currentThread().getId()+"准备执行push中的notifyAll()");
        notifyAll();
        TimeUnit.SECONDS.sleep(1);
        System.out.println(Thread.currentThread().getId()+"完成执行push中的notifyAll()");
    }

    // 消费一个馒头
    public synchronized Mantou pop() throws InterruptedException {
        while(content.size()==0){
            System.out.println(Thread.currentThread().getId()+"准备执行pop中的wait()");
            wait();
            System.out.println(Thread.currentThread().getId()+"完成执行pop中的wait()");
        }
        Mantou mantou = content.remove(0);
        System.out.println(Thread.currentThread().getId()+"消费者取出了一个物品："+this);
        System.out.println(Thread.currentThread().getId()+"准备执行pop中的notifyAll()");
        notifyAll();
        TimeUnit.SECONDS.sleep(1);
        System.out.println(Thread.currentThread().getId()+"完成执行pop中的notifyAll()");
        return mantou;
    }

    @Override
    public String toString() {
        return "Basket{" +
                "current=" + content.size()+"}";
    }
}
